﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace TK.Common.FFmpeg
{
    /// <summary>
    /// ffmpeg
    /// </summary>
    public class FFmpegService
    {
        private readonly ProcessStartInfo _cmdFFmpeg;
        private readonly ProcessStartInfo _cmdFFprobe;

        /// <summary>
        /// ctor
        /// </summary>
        public FFmpegService()
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    var baseDir = Path.Combine(AppContext.BaseDirectory, "FFmpeg");
                    _cmdFFmpeg = new ProcessStartInfo(Path.Combine(baseDir, "ffmpeg.exe"));
                    _cmdFFprobe = new ProcessStartInfo(Path.Combine(baseDir, "ffprobe.exe"));
                }
                else
                {
                    _cmdFFmpeg = new ProcessStartInfo("/usr/bin/ffmpeg");
                    _cmdFFprobe = new ProcessStartInfo("/usr/bin/ffprobe");
                }

                _cmdFFmpeg.RedirectStandardError = false;
                _cmdFFmpeg.RedirectStandardOutput = true;
                _cmdFFmpeg.UseShellExecute = false;
                _cmdFFmpeg.CreateNoWindow = true;
                _cmdFFprobe.RedirectStandardError = false;
                _cmdFFprobe.RedirectStandardOutput = true;
                _cmdFFprobe.UseShellExecute = false;
                _cmdFFprobe.CreateNoWindow = true;
            }
            catch { }
        }

        /// <summary>
        /// 获取音视频格式化消息show_format;
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public async Task<VideoFormatInfoDto> GetShowFormatInfoAsync(string filePath)
        {
            var commandParams = $"-i {filePath} -v error -show_format -print_format json";
            _cmdFFprobe.Arguments = commandParams;

            using (var process = new Process())
            {
                process.StartInfo = _cmdFFprobe;
                process.Start();
                var result = await process.StandardOutput.ReadToEndAsync();
                process.WaitForExit(10000);
                try
                {
                    var info = System.Text.Json.JsonSerializer.Deserialize<VideoFormatInfoDto>(result);
                    return info;
                }
                catch (Exception)
                {
                    return new VideoFormatInfoDto { Error = result };
                }
            }
        }

        /// <summary>
        /// 视频截图，返回截图路径,错误返回空
        /// 
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public async Task<string> ScreenShortAsync(string filePath)
        {
            var outPath = Path.Combine(AppContext.BaseDirectory, $"{Guid.NewGuid():N}.jpg");
            var commandParams = $"-i {filePath} -y -q:v 7 -f image2 -t 0.001 {outPath}";
            _cmdFFmpeg.Arguments = commandParams;

            using (var process = new Process())
            {
                process.StartInfo = _cmdFFmpeg;
                process.Start();
                _ = await process.StandardOutput.ReadToEndAsync();
                process.WaitForExit(10000);
            }

            return File.Exists(outPath) ? outPath : string.Empty;
        }
    }
}
